import json
from pyecharts import options as opts
from pyecharts.charts import Graph
import webbrowser

# 1. 加载所有数据文件
with open('data/math_knowledge.json', 'r', encoding='utf-8') as f:
    knowledge_data = json.load(f)

with open('data/math_concept_relations_enhanced.json', 'r', encoding='utf-8') as f:
    relations_data = json.load(f)

with open('data/math_application_examples.json', 'r', encoding='utf-8') as f:
    apps_data = json.load(f)

# 2. 准备节点和边数据
nodes = []
edges = []
node_name_map = {}  # 用于映射完整路径到显示名称
existing_edges = set()  # 避免重复边

# 添加知识节点（按教育阶段分类）
knowledge_nodes = {}
for level, categories in knowledge_data.items():
    for category, concepts in categories.items():
        for concept, sub_concepts in concepts.items():
            # 主概念节点
            node_id = f"{level}.{category}.{concept}"
            display_name = concept  # 只显示概念名称
            node_name_map[node_id] = display_name
            knowledge_nodes[node_id] = {
                "name": display_name,
                "category": category,
                "level": level
            }
            nodes.append({
                "name": node_id,
                "symbolSize": 20,
                "label": opts.LabelOpts(formatter=display_name),
                "category": category,
                "itemStyle": {
                    "color": "#4E79A7" if level == "大学数学基础" 
                    else "#F28E2B" if level == "人工智能数学基础" 
                    else "#59A14F"
                },
                "tooltip": opts.TooltipOpts(formatter=f"{node_id}")
            })
            
            # 子概念节点
            for sub in sub_concepts:
                sub_id = f"{node_id}.{sub}"
                node_name_map[sub_id] = sub
                nodes.append({
                    "name": sub_id,
                    "symbolSize": 15,
                    "label": opts.LabelOpts(formatter=sub),
                    "category": category,
                    "itemStyle": {
                        "color": "#4E79A7" if level == "大学数学基础" 
                        else "#F28E2B" if level == "人工智能数学基础" 
                        else "#59A14F"
                    },
                    "tooltip": opts.TooltipOpts(formatter=f"{sub_id}")
                })
                edge_key = f"{node_id}->{sub_id}"
                if edge_key not in existing_edges:
                    edges.append({
                        "source": node_id,
                        "target": sub_id,
                        "label": {"show": False}
                    })
                    existing_edges.add(edge_key)

# 添加应用实例节点
for app in apps_data["application_examples"]:
    app_id = f"应用.{app['example_id']}"
    display_name = app['title']
    node_name_map[app_id] = display_name
    nodes.append({
        "name": app_id,
        "symbolSize": 25,
        "label": opts.LabelOpts(formatter=display_name),
        "category": "应用实例",
        "itemStyle": {"color": "#E15759"},
        "tooltip": opts.TooltipOpts(formatter=f"应用ID: {app_id}\n描述: {app['description']}")
    })
    # 连接相关概念
    for concept in app["related_concepts"]:
        edge_key = f"{app_id}->{concept}"
        if edge_key not in existing_edges:
            edges.append({
                "source": app_id,
                "target": concept,
                "label": {"show": True, "formatter": "应用场景"}
            })
            existing_edges.add(edge_key)

# 添加math_concept_relations_enhanced.json中的关系
for relation in relations_data["relations"]:
    source = relation["source"]
    target = relation["target"]
    edge_key = f"{source}->{target}"
    
    if edge_key not in existing_edges:
        edges.append({
            "source": source,
            "target": target,
            "label": {
                "show": True,
                "formatter": relation["description"],
                "fontSize": 10
            },
            "lineStyle": {
                "type": "dashed" if relation["relation_type"] == "learning_path" else "solid",
                "width": 1.5 if relation["relation_type"] == "cross_domain" else 1
            }
        })
        existing_edges.add(edge_key)

# 3. 创建知识图谱
categories = [
    {"name": "代数"}, {"name": "几何"}, {"name": "概率统计"},
    {"name": "三角函数"}, {"name": "微积分"}, {"name": "线性代数"},
    {"name": "离散数学"}, {"name": "应用实例"}
]

graph = (
    Graph(init_opts=opts.InitOpts(width="1800px", height="1000px"))
    .add(
        "",
        nodes=nodes,
        links=edges,
        categories=categories,
        repulsion=300,
        edge_label=opts.LabelOpts(
            position="middle",
            formatter="{c}",
            font_size=10
        ),
        linestyle_opts=opts.LineStyleOpts(width=0.5, curve=0.3),
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="数学知识图谱（完整关系）", subtitle="包含所有概念和应用关系"),
        legend_opts=opts.LegendOpts(orient="vertical", pos_left="2%"),
        tooltip_opts=opts.TooltipOpts(trigger="item"),
    )
)

# 4. 保存并打开HTML文件
graph.render("math_knowledge_graph_full.html")
webbrowser.open("math_knowledge_graph_full.html")
